<?php


namespace app\admin\controller;


use app\admin\library\Auth;
use app\admin\model\AuthGroup;
use app\admin\model\WanderRecord;
use app\BaseController;
use app\Request;
use fast\Tree;
use think\facade\Db;
use think\facade\View;

class Wander extends BaseController
{
    /**
     * @var \app\admin\model\AuthGroup
     */
    protected $model = null;
    //当前登录管理员所有子组别
    protected $childrenGroupIds = [];

    public function initialize()
    {
        parent::initialize();
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);
        $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();
        Tree::instance()->init($groupList);
    }

    //列表读取
    public function index(Request $request)
    {
        if ($request->isAjax()) {
            //获取每页显示的条数
            $limit = $request->param('limit');
            //获取当前页数
            $page = $request->param('page');
            $list = WanderRecord::with(['wander' => ['promoterAdmin', 'abutmentAdmin', 'superiorAdmin']])->where(['run_id'=>$this->auth->id])->paginate($limit, false, ['page' => $page])->each(function ($item, $key) {
                $item['title'] = $item['wander']['title'] ?? 'unknown';
                $item['describe'] = $item['wander']['describe'] ?? 'unknown';
                $item['content'] = $item['wander']['content'] ?? 'unknown';
                $item['status_type'] = Wf::status($item['examine_status']) ?? 'unknown';
                $item['promoter_name'] = $item['wander']['promoterAdmin']['nickname'] ?? 'unknown';
                $item['abutment_name'] = $item['wander']['abutmentAdmin']['nickname'] ?? 'unknown';
                $item['abutment_id'] = $item['wander']['abutment_id'] ?? 'unknown';
            })->toArray();
            return json(['code' => 200, 'msg' => '', 'total' => $list['total'], 'data' => $list['data']]);
        }
    }


    //发布流程单
    public function add(Request $request)
    {
        $group = AuthGroup::where(['level' => 2, 'status' => 1])->select();
        if ($request->isAjax()) {
            $data = $request->param();
            if ($data['period']) {
                $time = explode('~', $data['period']);
                $data['begin_time'] = reset($time);
                $data['end_time'] = end($time);
            }
            $data['promoter_id'] = $this->auth->id;
            $res = \app\admin\model\Wander::create($data);
            if ($res) {
                WanderRecord::create([
                    'wander_id' => $res->id,
                    'btn' => WanderRecord::BTN_ONT,
                    'run_id' => $data['promoter_id']
                ]);
            }
            return json(['code' => 200, 'url' => '', 'msg' => '成功创建流转单！']);
        }
        View::assign('group', $group);
        return View::fetch('form/wander/add');
    }

    //获取用户
    public function form_select(Request $request)
    {
        $id = $request->param('id');
        $getAdminIds = AuthGroup::getChildrenIds($id);
        // array_unshift($getAdminIds, $id); //自身加进去 领导级别
        $authGroupList = \app\admin\model\AuthGroupAccess::field('uid')->where('group_id', 'in', $getAdminIds)
            ->select()->toArray();
        $childrenGroupIds = [];
        foreach ($authGroupList as $k => $v) {
            $childrenGroupIds[] = $v['uid'];
        }
        $adminList = \app\admin\model\Admin::where('id', 'in', $childrenGroupIds)->select()->toArray();
        return json_encode($adminList);
    }


    //详情读取
    public function read(Request $request)
    {
        $wander_id = $request->param('wander_id');
        $res = \app\admin\model\Wander::with(['promoterAdmin', 'abutmentAdmin', 'superiorAdmin', 'abutmentGroup'])->find($wander_id);
        $res['status_ty'] = Wf::status($res['finish_status']);
        View::assign('model', $res);
        return View::fetch('form/wander/read');
    }

    //编辑页面
    public function edit(Request $request)
    {
        $wander = \app\admin\model\Wander::with(['promoterAdmin', 'abutmentAdmin', 'superiorAdmin', 'abutmentGroup'])->find($request->param('id'));
        $wander['period'] = date("Y-m-d", strtotime($wander['begin_time'])) . ' ~ ' . date("Y-m-d", strtotime($wander['end_time']));
        $group = AuthGroup::where(['level' => 2, 'status' => 1])->select();
        if ($request->isAjax()) {
            $data = $request->param();
            if ($data['period']) {
                $time = explode('~', $data['period']);
                $data['begin_time'] = reset($time);
                $data['end_time'] = end($time);
            }
            $data['promoter_id'] = $this->auth->id;
            $res = \app\admin\model\Wander::update($data);
            return json(['code' => 200, 'url' => '', 'msg' => '成功更新流转单！']);
        }
        View::assign('model', $wander);
        View::assign('group', $group);
        return View::fetch('form/wander/edit');
    }

    //删除页面
    public function del($ids = null)
    {
        if ($ids) {
            $ids_arr = explode(',', $ids);
            foreach ($ids_arr as $key => $value) {
                $wander = \app\admin\model\Wander::with('wanderRecord')->find($value);
                if ($wander) {
                    $wander->together(['wanderRecord'])->delete();
                }
            }
            return json(['code' => 200, 'url' => '', 'msg' => '成功删除流转单！']);
        }
    }

    //审核页面
    public function examine(Request $request)
    {
        $wander = \app\admin\model\Wander::with(['promoterAdmin', 'abutmentAdmin', 'superiorAdmin', 'abutmentGroup'])->find($request->param('wander_id'));
        $wander['period'] = date("Y-m-d", strtotime($wander['begin_time'])) . ' ~ ' . date("Y-m-d", strtotime($wander['end_time']));
        $this_group = $this->auth->getGroupIds();
        if (count($this_group) > 1) {
            $group_id = end($this_group);
        } else {
            $group_id = reset($this_group);
        }
        $group_parent = Tree::instance()->getParents($group_id, false);
        $group = AuthGroup::where(['level' => 2, 'status' => 1])->select();
        if ($request->isAjax()) {
            $params = $request->param();
            if ($params['is_superior'] == 0) { //不需要上级审核
                //获取对接人的角色
                $this_group = $this->auth->getGroupIds($params['abutment_id']);
                //区别1对多角色
                if (count($this_group) > 1) {
                    $group_id = end($this_group);
                } else {
                    $group_id = reset($this_group);
                }
                //获取父级角色
                $group_parent = Tree::instance()->getParent($group_id);
                //获取该角色对应的用户信息
                $adminList = Db::name("auth_group_access")
                    ->alias("aga")
                    ->join("admins a", "aga.uid=a.id")
                    ->field("a.*")
                    ->where("aga.group_id", reset($group_parent)['id']) //1为角色组ID
                    ->select()->toArray();
                //取用户id
                $parent_admin = reset($adminList)['id'] ?? 0;
            } else { //上级审核
                //获取该角色对应的用户信息
                $adminList = Db::name("auth_group_access")
                    ->alias("aga")
                    ->join("admins a", "aga.uid=a.id")
                    ->field("a.*")
                    ->where("aga.group_id", $params['superior_id']) //角色组ID
                    ->select()->toArray();
                //取用户id
                $parent_admin = reset($adminList)['id'] ?? 0;
            }
            $data = [
                'wander_id' => $params['id'],
                'run_id' => $parent_admin,
                'btn' => WanderRecord::BTN_TWO,
                'examine_status' => WanderRecord::STATUS_ONE
            ];
            $res = WanderRecord::create($data);
            if ($res) {
                \app\admin\model\Wander::update([
                    'id' => $params['id'],
                    'is_superior' => $params['is_superior'],
                    'superior_id' => $params['superior_id'],
                    'finish_status' => WanderRecord::STATUS_ONE,
                ]);
            }
            return json(['code' => 200, 'url' => '', 'msg' => '提交成功！']);
        }

        //当登录人与对接人相同的时候按钮变为完成
        View::assign('model', $wander);
        View::assign('group', $group);
        View::assign('group_parent', $group_parent);
        View::assign('group_parent_count', count($group_parent));
        return View::fetch('form/wander/examine/index');
    }

    //完成流转单审核（End）
    public function accomplish(Request $request)
    {
        $data = $request->param();
        $data['examine_status'] = WanderRecord::BTN_FOUR;
        $res = WanderRecord::update($data);
        if ($res) {
            \app\admin\model\Wander::update([
                'id' => $data['wander_id'],
                'finish_status' => WanderRecord::BTN_FOUR
            ]);
        }
        return json(['code' => 200, 'url' => '', 'msg' => '感谢您的配合！']);

    }

    //拒绝流转单审核
    public function refuse(Request $request)
    {
        $data = $request->param();
        $data['examine_status'] = WanderRecord::BTN_THREE;
        $res = WanderRecord::update($data);
        if ($res) {
            \app\admin\model\Wander::update([
                'id' => $data['wander_id'],
                'finish_status' => WanderRecord::BTN_THREE
            ]);
        }
        return json(['code' => 200, 'url' => '', 'msg' => '感谢您的配合！']);
    }

}